// 用户中心配置
import {snowflakeGenerator} from 'snowflake-id-js'
import draggable from 'vuedraggable'
import { saveMicroPage,viewPageByCategory } from '@/api/shoppingMall/feature'
import { getCpTpPermissionGroupList, getCpTpPermissionByGroup, addTpPermissionGroup, delTpPermissionGroup, addTpPermission } from '@/api/authority'
export default {
  name: 'MdiCollaboration',
  components: {
    draggable,
    iconFont:()=>import('@/components/icon-font'),
    chooseImages: () => import('@/components/new-choose-images/index.vue'),
    chooseFeature: () => import('@/components/choose-feature/index.vue')
  },
  data() {
    return {
      isDialogIcon: false,
      isGroupDialog: false,
      isAppDialog: false,
      isICon: true,
      iconUrl:'',
      isGetChooseData: false, // 是否可以返回微页面
      dialogChoosePages: false, // 自定义页面弹窗
      cpTpPermissionGroupList: [],
      cpTpPermissionList: [],
      index1:0,
      index2:0,
      canChooseImagesNum: 1, // 可以添加的图片数量
      isSaving: false, // 是否正在保存
      dialogVisible: false,
      // head的颜色列表
      headColorList: ['#b2b2b2', '#e36657', '#654b65', '#a3c87b', '#77b1f2', '#464545', '#f1aab5'],
      showOrHider: [{ key: 1, title: '显示' }, { key: 2, title: '隐藏' }],
      isShowHeadPop: false,
      currentPanel: '1',
      moduleList: [{
          type: "config",
          dataField: {
            isShow: true,
            disabled: true,
            key: 'topNavBar',
            moduleName: '页面设置',
            category: 15,
            title: '协同页面设置',
            desc: '',
            backColor: '#FFFFFF',
            colorSetting: 1,
            contentColor: '#000000',
            globalBackColor: '#FFFFFF',
            globalContentColor: '#000000',
            style: '1'
          }
        },{
          type: 'imageMenu',
          dataField: {
            isShow: false,
            key: 'imageMenu',
            moduleName: '图片导航',
            item: [
              {
                title: '图片菜单',
                height: 80,
                link: {},
                url: require('@/assets/commons/welcome.png')
              }
            ]
          }
        },{
          type: 'tpApp',
          dataField: {
            isShow: true,
            disabled: true,
            key: 'tpApp',
            moduleName: '应用设置',
            item: [{
                icon: {
                  type: 1,
                  url: '#icon-a-ziyuan111',
                  appUrl:'t-icon-a-ziyuan111'
                },
                isShow: true,
                title: '应用',
                url: {
                  style: '1',
                }
              },{
                icon: {
                  type: 1,
                  url: '#icon-a-ziyuan10',
                  appUrl:'t-icon-a-ziyuan10'
                },
                isShow: true,
                title: '应用',
                url: {
                  style: '1',
                }
              },{
                icon: {
                  type: 1,
                  url: '#icon-a-ziyuan121',
                  appUrl:'t-icon-a-ziyuan121'
                },
                isShow: true,
                title: '应用',
                url: {
                  style: '1',
                }
              },{
                icon: {
                  type: 1,
                  url: '#icon-a-ziyuan141',
                  appUrl:'t-icon-a-ziyuan141'
                },
                isShow: true,
                title: '应用',
                url: {
                  style: '1',
                }
              }
            ]
          }
        },
        {
          type: 'taskFlow',
          dataField: {
            isShow: true,
            disabled: true,
            key: 'taskFlow',
            moduleName: '流程任务',
            itemShowNum: 4,
            item: [{
              isShow: true,
              url: require('@/assets/cms/task_flow.png')
            }]
          }
        },
        {
          type: 'billKanban',
          dataField: {
            isShow: true,
            disabled: true,
            key: 'billKanban',
            moduleName: '单据看板',
            itemShowNum: 4,
            item: [{
              isShow: true,
              url: require('@/assets/cms/bill_kanban.png')
            }]
          }
        }
      ],
      addNewMenu: {
        icon: {
          style: '1',
          url: ''
        },
        isShow: true,
        title: '',
        url: {
          style: '1',
          h5: '',
          appId: '',
          pagePath: ''
        }
      },
      // 当前编辑
      currentItem: {
        info: {}
      },
      permissionGroupParams: {},
      permissionAppParams: {},
      editableTabsIndex: 0,
      dialogEdit: false,
      id:'',
      isType:null,
      isIcon:false,
      isImg:false
    }
  },
  computed: {},
  mounted () {
    this.getCpTpPermissionGroupList()
    this.getInfo()
  },
  methods: {
    getCpTpPermissionGroupList() {
      getCpTpPermissionGroupList({}).then(res => {
        if(res){
          this.cpTpPermissionGroupList = res
          this.editableTabsIndex = 0
          const firstGroupid = this.cpTpPermissionGroupList[0].id
          if(firstGroupid) {
            this.getCpTpPermissionByGroup(firstGroupid)
          }
        }
      })
    },
    getCpTpPermissionByGroup (groupid) {
      this.cpTpPermissionList = []
      getCpTpPermissionByGroup({groupId: groupid}).then(res => {
        if(res){
          this.cpTpPermissionList = res
        }
      })
    },
    getInfo(){
      viewPageByCategory({ id: 15 }).then(res => {
        this.id = res.id
        if(res.moduleList.length > 0){
          this.moduleList = res.moduleList
        }
      })
    },
    addPermissionGroup() {
      const generator = snowflakeGenerator(512)
      let newId = generator.next().value
      this.permissionGroupParams = {
        name: '',
        id: newId,
        sort: this.cpTpPermissionGroupList.length + 1
      },
       this.isGroupDialog = true
    },
    savePermissionGroup() {
      if(this.permissionGroupParams.name == ''){
          alert('组名不能为空')
          return false
      }
      addTpPermissionGroup(this.permissionGroupParams).then(res => {
        if (res) {
          if (res.code) {
            this.$message.error(`${res.msg}`)
          } else {
            this.$message.success('保存成功!')
            this.cpTpPermissionGroupList.push(this.permissionGroupParams)
            this.editableTabsIndex = this.cpTpPermissionGroupList.length - 1
            this.isGroupDialog = false
          }
        }
      })
    },
    changeTab(tab, event) {
      this.editableTabsIndex = tab.index
      const groupItem = this.cpTpPermissionGroupList[tab.index]
      if(groupItem) {
         this.getCpTpPermissionByGroup(groupItem.id)
      }
    },
    removeTab(tabIndex){
      if(this.cpTpPermissionGroupList[tabIndex]){
        const groupItem = this.cpTpPermissionGroupList[tabIndex]
        const groupId = groupItem.id
        const appList = groupItem.appList
        if(appList && appList.length > 0){
           alert('该分组下包含有应用，不能删除')
           return false
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delTpPermissionGroup({id: groupId}).then(res => {
            if (res) {
              if (res.code) {
                this.$message.error(`${res.msg}`)
              } else {
                let thisTabs = this.cpTpPermissionGroupList
                let activeName = this.editableTabsIndex
                if (activeName === tabIndex) {
                   thisTabs.forEach((tab, index) => {
                     if (tab.name === tabIndex) {
                       let nextTab = thisTabs[index + 1] || thisTabs[index - 1];
                       if (nextTab) {
                         activeName = nextTab.name;
                       }
                     }
                   });
                }
                this.editableTabsIndex = activeName
                this.cpTpPermissionGroupList = thisTabs.filter(tab => tab.name !== targetName)
                this.$message.success('删除成功!')
              }
            }
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        })
       }
    },
    addPermissionApp() {
      const generator = snowflakeGenerator(512)
      let newId = generator.next().value
      const curIndustry = localStorage.getItem('industry')
      if(this.cpTpPermissionGroupList){
         this.curselectedGroup = this.cpTpPermissionGroupList[this.editableTabsIndex]
         if(this.curselectedGroup.appList){
           this.groupAppCount = this.curselectedGroup.appList.length
         }else{
            this.groupAppCount = 0
         }
      }else{
         this.groupAppCount = 0
      }
      this.permissionAppParams = {
        name: '',
        id: newId,
        icon: '',
        parentId: this.curselectedGroup.id,
        industry: curIndustry,
        module: 'tenant',
        routeType: 2,
        type: 2,
        target: 2,
        sort: this.groupAppCount
      },
       this.isAppDialog = true
    },
    savePermissionApp() {
      if(this.permissionAppParams.name == ''){
          alert('应用不能为空')
          return false
      }
      addTpPermission(this.permissionAppParams).then(res => {
        if (res) {
          if (res.code) {
            this.$message.error(`${res.msg}`)
          } else {
            this.$message.success('保存成功!')
            this.getCpTpPermissionByGroup(this.editableTabsIndex)
            this.isAppDialog = false
          }
        }
      })
    },
    delPermissionApp(id){
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delTpPermission({id: id}).then(res => {
          if (res) {
            if (res.code) {
              this.$message.error(`${res.msg}`)
            } else {

            }
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })

    },
    imageClick(index1,index2){
      this.$delete(this.moduleList[index1].dataField.item, index2)
    },
    // 保存
    save(){
      this.isSaving = true
      const moduleList = {
        id: this.id,
        operType: 2,
        moduleList: this.moduleList
      }
      saveMicroPage(moduleList).then(res => {
        this.isSaving = false
        this.$message.success('发布成功')
        this.getInfo()
      })
    },
    addMenuClick(){
      this.isType = 1
      this.dialogVisible = true
      Object.keys(this.addNewMenu).forEach(key =>{
        if(typeof this.addNewMenu[key] == 'object'){
         Object.keys(this.addNewMenu.icon).forEach(key1 => {
           this.addNewMenu.icon[key1] = ''
         })
         Object.keys(this.addNewMenu.url).forEach(key1 => {
           this.addNewMenu.url[key1] = ''
         })
        }else{
          this.addNewMenu[key] = ""
        }
      })
      this.addNewMenu.icon.style = '1'
      this.addNewMenu.url.style = '1'
    },
    // 选择图标
    iconClick(){
      this.isDialogIcon = true
      this.isShowIcon()
    },
    // 确定 图标
    iconChooseModel(){
      switch(this.isType){
        case 1:
          this.addNewMenu.icon.url = this.iconUrl
          this.$set(this.addNewMenu.icon,'appUrl',this.iconUrl.replace('#icon', 't-icon'))
          break
        case 2:
          this.currentItem.info.icon.url = this.iconUrl
          this.$set(this.currentItem.info.icon,'appUrl',this.iconUrl.replace('#icon', 't-icon'))
          break
      }

      this.isDialogIcon = false
    },
    iconBox(val){
      this.iconUrl = val
    },
    isShowIcon(){
      this.isICon = false
      this.$nextTick(()=>{
        this.isICon = true
      })
    },
    // 背景图像
    choiceClick(index){
      this.index1 = index
      this.index2 = ''
      this.$refs.pics.dialog = true
    },
    // 图片导航
    changeImg(index1,index2) {
      this.index1 = index1
      this.index2 = index2
      this.$refs.pics.dialog = true
      this.isImg = true
    },
    ImgClick(){
      this.$refs.pics.dialog = true
      this.isImg = false
    },
    getPicsUrl(arr) {
      if(this.index2 === ''){
        this.moduleList[this.index1].dataField.boxBackgroundImage = arr[0]
      }else{
        if(this.isImg){
          this.moduleList[this.index1].dataField.item[this.index2].url = arr[0]
        }else{
          console.log(this.currentItem)
          this.currentItem.info.icon.url = arr[0]
        }
      }
    },
    chooseImagesEnd($item) {
    },
    // 微页面
    choosePage(index1,index2,link) {
      this.index1 = index1
      this.index2 = index2
      this.dialogChoosePages = true
    },
    confirmClick() {
      let data = this.$refs.feature.currentchooseFeatures
      const microTitle = data.type === 0 && '系统页面' || data.type === 1 && '功能页面' || data.type === 2 && '商品详情' || data.type === 3 && '商品活动'
      let obj = {
        id: data.id,
        type: data.type,
        title: data.title,
        link: data.path,
        microTitle: microTitle,
      }
      if(this.index1 == ''){
        this.addNewMenu.url = {...this.addNewMenu.url,...obj}
      }else{
        this.$set(this.moduleList[this.index1].dataField.item[this.index2], 'link', obj)
      }
      this.dialogChoosePages = false
      this.$forceUpdate()
    },
    dragOnMove($data) {
      return $data.relatedContext.element.dataField.key !== 'topNavBar'
    },
    handlerClickModule(item) {
      if (this.currentPanel === item.dataField.key) {
        this.currentPanel = ''
        return
      }
      this.currentPanel = item.dataField.key
    },
    // push menu
    handlePushMenu() {
      this.$refs['addMenu'].validate((valid) => {
        if (valid) {
          let menuObj = this.moduleList.find(item => item.type === 'menu')
          menuObj.dataField.item.push(this.addNewMenu)
          this.dialogVisible = false
        } else {
          return false
        }
      })
    },
    handleTapHeadColor(item, colorItem, colorIndex) {
      item.colorIndex = colorIndex + 1
      item.systemColor = colorItem

      let pop = this.$refs.popHead
      if (pop && pop.length) {
        pop[0].doClose()
      }
    },
    // 添加图片菜单
    handleAddImageMenu($list) {
      if ($list && $list.length >= 10) return
      $list.push({
        title: '图片菜单' + $list.length,
        link: {},
        url: require('@/assets/commons/welcome.png')
      })
    },
    // 用户资产 编辑
    assetEdit(meItem, meIndex, index){
      this.dialogEdit = true
      this.isIcon = true
      this.currentItem = {
        meIndex, index,
        info: JSON.parse(JSON.stringify(meItem))
      }
    },
    // 点击编辑
    handlerEdit(meItem, meIndex, index) {
      this.isIcon = false
      this.currentItem = {
        meIndex, index,
        info: JSON.parse(JSON.stringify(meItem))
      }
      this.dialogEdit = true
      this.isType = 2
    },
    // 修改名称、图标
    handlerSave() {
      let { currentItem } = this
      this.moduleList[currentItem.index].dataField.item[currentItem.meIndex] = currentItem.info
      this.dialogEdit = false
    }
  }
}
